package com.by.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.by.context.UserContext;
import com.by.entity.Order;
import com.by.entity.OrderItem;
import com.by.mapper.LiOrderMapper;
import com.by.mapper.OrderItemMapper;
import com.by.service.OrderService;
import com.by.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<LiOrderMapper, Order> implements OrderService {


    @Autowired
    LiOrderMapper liOrderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    /**
     * 保存订单
     * @param order
     * @return
     */
    @Override
    public boolean save(Order order) {
        //订单是根据用户生成的，所以会员id是需要保存

        //查看用户是否登录

        //查看传入的订单是否为空
        if (order==null)return false;
        //用户id
        int id = UserContext.get().getId();
        //******获取用户地址*****
        //根据id查询地址
        Order order1 = order.setOrderAddr("测试地址");


        //总价格
        double total = 0;

        //保存订单明细
        List<OrderItem> orderItemList = order.getOrderItemList();
        for (OrderItem item : orderItemList) {
            item.setShopId(order.getShopId())
                    .setOrderId(order.getUserId());
            int itemInsert = orderItemMapper.insert(item);
            double i = (double)item.getSpuTotalAmount() * item.getCount();
            total+=i;
            Assert.isZero(itemInsert,"保存订单"+item.getOrderItemId()+"明细失败");
        }

        //设置总值
        order.setTotal(total);
        //
        int insert = liOrderMapper.insert(order);
        Assert.isZero(insert,"保存订单失败");

        return false;
    }
}
